<template>
	<view class="">
		<!-- 内容 -->
		<view class="concent_box">
			<view class="inibox">
				<view class="inibox_in">
					<view class="inibox_tt_a" hover-class="inibox_ttacv" @click="tobelFn" v-if="lanname == ''">点击连接设备
					</view>
					<view class="inibox_tt_b" hover-class="inibox_ttacv" @click="lampRFn" v-if="lanname != ''">点击断开设备
					</view>
				</view>
				<view :class="['lights-box', lightsOn ? 'lights-on' : 'lights-off']" @click="iniIFFn">
					{{ lightsOn ? '设备已初始化' : '设备未初始化' }}
				</view>
			</view>
			<view class="zhuanbox">
				<!-- 紧急暂停 -->
				<view class="control-btn" @click="stopPause">
					<view class="">紧急暂停</view>
				</view>
			</view>
			<!-- 转速 -->
			<view class="rotatzhuns">
				<view class="rotatzhflax">
					<view class="">
						<uni-data-checkbox v-model="rotatvalue" selectedColor="#5e8c7e" :localdata="rotatdata"
							mode="tag"></uni-data-checkbox>
					</view>
				</view>
				<view class="zhunsbtn" @click="switchMode">
					切换转速
				</view>
			</view>
			<!-- 圈数 -->
			<view class="rotatquans">
				<view class="rotatzhflax">
					<view class="">
						<uni-data-checkbox v-model="numberOfLaps" selectedColor="#51517a" :localdata="numberOfdata"
							mode="tag" @change="numberOfRunningLaps"></uni-data-checkbox>
					</view>
				</view>
				<view class="zhunsbtn">
					运行圈数
				</view>
			</view>
			<!-- 圈数 -->
			<view class="real_simu_c">
				<view class="">
					设备圈数：
				</view>
				<view class="real_r_a">
					<view>{{numberOfCircles}}</view>
					<view>圈</view>
				</view>
			</view>
			<view class="real_simu_a">
				<view class="">
					螺杆导程：
				</view>
				<view class="real_r_a">
					<view>{{rotationalSpeedRatio}}</view>
					<view>cm</view>
				</view>
			</view>
			<!-- 			<view class="real_simu_b">
				<view class="">
					闸门开合：
				</view>
				<view class="real_r_a">
					<view>{{gateOpeningAndClosing}}</view>
					<view>m</view>
				</view>
			</view> -->
			<view class="initial_position">
				<view class="">
					运行距离：
				</view>
				<view class="real_r_a">
					<view class="real_rin">
						<u--input placeholder="输入" type="digit" inputAlign="center" border="none"
							v-model="inputPosition"></u--input>
					</view>
					<view class="real_rtt">
						cm
					</view>
				</view>
				<view class="">
					<u-button text="确定" color="#17a2b8" @click="modifyInitialFn"></u-button>
				</view>
			</view>
			<!-- 初始位置 -->
			<u-modal :show="innitiaF" title="修改运行距离" @confirm="cinfinitialIF" @cancel="infcaninitialIF"
				showCancelButton></u-modal>
			<!-- 运行距离 -->
			<view class="card-modu_bnox">
				<view class="indats">
					<view class="card-box indah">
						<view class="card-input">
							{{executionDistance}}
						</view>
						<!-- 单位 -->
						<view class="unit">圈</view>
					</view>
					<!-- 运行按钮 -->
					<view class="run-btt indah">
						运 行 圈 数
					</view>
				</view>
				<view class="card-module">
					<!-- 上升 -->
					<!-- 					<view class="card-container_up">
						<view class="rise-btn indah" @click="handleUp">
							<text class="btn-text">↑</text>
							<text class="btn-text">上升</text>
						</view>
					</view> -->
					<!-- 下降 -->
					<!-- 					<view class="card-container_dn">
						<view class="rise-pd indah" @click="handleDown">
							<text class="btn-text">↓</text>
							<text class="btn-text">下降</text>
						</view>
					</view> -->
					<!-- 运行 -->
					<view class="card-container_Run">
						<!-- 下降按钮 -->
						<view class="clean-game-btn success" @click="handleRun">
							运行
						</view>
					</view>

				</view>

			</view>

		</view>

		<!-- 初始化电机 -->
		<u-modal :show="infIF" title="初始化设备" @confirm="cinfconfirmIF" @cancel="infcancelIF" showCancelButton></u-modal>
		<!-- 测试 -->

		<!-- 测试 -->
	</view>
</template>

<script>
	import dayjs from '@/common/dayjs.min.js'
	const SixUniTts = uni.requireNativePlugin("SmallSix-SixUniTts")
	export default {
		components: {

		},
		props: {
			message: 0 // 简写形式
		},
		data() {
			return {
				titlename: '',
				fontSize: '20px',
				rotationalSpeedRatio: 0, //转速比
				numberOfCircles: 0, //圈数
				infIF: false, //初始化
				deviceId: '', //蓝牙
				serviceId: '', //蓝牙
				characteristicId: '', //蓝牙
				fff: '', //蓝牙
				lanname: '', //蓝牙
				timerTmei: null, //定时器
				executionDistance: 100, //执行距离
				motorDistance: 0, //电机距离
				gateOpeningAndClosing: 0, //闸门开合
				rotatvalue: 1200, //转速
				rotatdata: [{
					text: '60转',
					value: 600
				}, {
					text: '120转',
					value: 1200
				}, {
					text: '180转',
					value: 1800
				}, {
					text: '240转',
					value: 2400
				}],
				modeSwitching: false, //模式切换
				lightsOn: false, //灯光
				innitiaF: false, //修改初始位置
				inputPosition: 0, //初始输入
				inputPosCalculation: 0, //初始计算
				initPosiIvuex: {}, //闸门内容
				modifyGate: true, //实时修改闸门
				numberOfLaps: 100, //运行圈数
				numberOfdata: [{
					text: '100圈',
					value: 100
				}, {
					text: '200圈',
					value: 200
				}, {
					text: '300圈',
					value: 300
				}, {
					text: '400圈',
					value: 400
				}],
			}
		},
		onShow() {
			console.log('进入页面');
		},
		onUnload() {
			console.log('卸载');
			// 暂停
			this.riseDevFnDestroy()
			clearInterval(this.timerTmei)
			// 销毁语音
			SixUniTts.destroy()
		},
		mounted() {
			// 初始化
			SixUniTts.initSixUniTts(res => {})
			console.log('////////////',this.message);
			this.reductionRatio = this.message.reductionRatio
		},
		methods: {
			// 输入圈数
			numberOfRunningLaps() {
				this.executionDistance = this.numberOfLaps
			},
			// 运行距离位置
			modifyInitialFn() {
				this.innitiaF = true
			},
			// 运行距离确认
			cinfinitialIF() {
				let nub = this.inputPosition / this.numberOfCircles
				this.rotationalSpeedRatio = this.roundAndTrim(nub)
				this.innitiaF = false
				// 子传父
				let obj = {}
				obj.rotationalSpeedRatio = this.rotationalSpeedRatio //转速比
				obj.inputPosition = this.inputPosition //高度
				this.$emit('childEvent', obj)
				console.log('运行距离修改');
			},
			// 运行距离取消
			infcaninitialIF() {
				this.innitiaF = false
			},
			// 运行
			handleRun() {
				this.handleUp()
			},
			// 上升
			handleUp() {
				if (this.executionDistance * 1 < 0) {
					uni.showToast({
						title: '输入错误',
						icon: "error",
						mask: true,
						duration: 1500
					});
					return
				}
				this.forwordFn(this.executionDistance)
				setTimeout(() => {
					clearInterval(this.timerTmei)
					this.timerTmei = setInterval(() => {
						this.aLLBrakeFnxx()
					}, 300)
				}, 1200)
			},
			// 紧急暂停
			stopPause() {
				clearInterval(this.timerTmei)
				console.log("暂停按钮点击");
				this.riseDevFnTHxx()
			},
			// 下降
			handleDown() {
				if (this.executionDistance*1 < 0) {
					uni.showToast({
						title: '输入错误',
						icon: "error",
						mask: true,
						duration: 1500
					});
					return
				}
				this.reversalFn(this.executionDistance)
				setTimeout(() => {
					clearInterval(this.timerTmei)
					this.timerTmei = setInterval(() => {
						this.aLLBrakeFnxx()
					}, 300)
				}, 1200)
			},
			// 询问地址脉冲状态
			aLLBrakeFnxx() {
				let brakea = ['0x01', '0x03', '0x60', '0x41', '0x00', '0x06', '0x8B', '0xDC']
				this.conbuffer(brakea)
			},

			// 遥控器
			// 纵向按钮正转
			forwordFn(data) {
				let numI = data * 1
				let nub = (numI * 1 * 10 * 1000).toFixed(0)
				let hexnub = this.decimalToHex(nub)
				let hexcrc = '0110607A000204' + this.strRepair(hexnub, 8)
				let crcStr = hexcrc + this.crc16(hexcrc)[1] + this.crc16(hexcrc)[0]
				let arrto = this.chunkStringByTwo(crcStr)
				let hexArr = this.ocstr(arrto)

				// “设置目标位置为”
				let targetPosition = hexArr
				//设置位置模式 01 06 60 60 00 01 56 14
				let positionMode = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x01', '0x56', '0x14']
				// 采集新位置并运行”
				let locationRun = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x1F', '0xD7', '0xD6']
				// 此处可先将控制字位 4 置 0，便于下一次快速采位
				let controlWordBit = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				console.log('脉冲xx', hexArr);
				// 给蓝牙传输
				this.conbuffer(targetPosition)
				setTimeout(() => {
					this.conbuffer(positionMode)
				}, 300)
				setTimeout(() => {
					this.conbuffer(locationRun)
				}, 600)
				setTimeout(() => {
					this.conbuffer(controlWordBit)
				}, 900)
			},
			// 纵向按钮反转
			reversalFn(data) {
				//电机 = 初始位-开合距离   负数
				//电机 = 开合距离-初始位   正数
				let dataNUB = (this.inputPosCalculation * 1 - data * 1).toFixed(1)
				let numI = dataNUB * 1
				let nub = (numI * 1 * 10 * 1000 / this.initPosiIvuex.speedRatio).toFixed(0)

				// 负数
				let numbnew = this.NumberOf1(-nub)
				let hex16 = this.binaryToHex(numbnew)
				// 正数
				let hexcrc = '0110607A000204' + this.strRepair(hex16, 8)
				let crcStr = hexcrc + this.crc16(hexcrc)[1] + this.crc16(hexcrc)[0]
				let arrto = this.chunkStringByTwo(crcStr)
				let hexArr = this.ocstr(arrto)

				// “设置目标位置为”
				let targetPosition = hexArr
				//设置位置模式 01 06 60 60 00 01 56 14
				let positionMode = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x01', '0x56', '0x14']
				// 采集新位置并运行”
				let locationRun = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x1F', '0xD7', '0xD6']
				// 此处可先将控制字位 4 置 0，便于下一次快速采位
				let controlWordBit = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']

				// 给蓝牙传输
				this.conbuffer(targetPosition)
				setTimeout(() => {
					this.conbuffer(positionMode)
				}, 300)
				setTimeout(() => {
					this.conbuffer(locationRun)
				}, 600)
				setTimeout(() => {
					this.conbuffer(controlWordBit)
				}, 900)
			},
			// 销毁暂停
			riseDevFnDestroy() {
				// 暂停运行
				let locationRunA = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x0F', '0xD7', '0x8A']
				// XX回零模式 01 06 60 60 00 06 17 D6  设置回零模式
				let locationRunB = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x06', '0x17', '0xD6']
				// XX回零模式 01 06 60 40 01 1F D6 46  暂停运行
				let locationRunC = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x1F', '0xD6', '0x46']
				// 给蓝牙传输
				this.conbuffer(locationRunA)
				setTimeout(() => {
					this.conbuffer(locationRunB)
				}, 300)
				setTimeout(() => {
					this.conbuffer(locationRunC)
				}, 900)
			},
			// 松开暂停
			riseDevFnTHxx() {
				uni.showToast({
					icon: 'loading',
					mask: true,
					title: '紧急暂停中...',
					duration: 1000
				});
				// 暂停运行
				let locationRunA = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x0F', '0xD7', '0x8A']
				// XX回零模式 01 06 60 60 00 06 17 D6  设置回零模式
				let locationRunB = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x06', '0x17', '0xD6']
				// XX回零模式 01 06 60 40 01 1F D6 46  暂停运行
				let locationRunC = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x1F', '0xD6', '0x46']
				// 给蓝牙传输
				this.conbuffer(locationRunA)
				setTimeout(() => {
					this.conbuffer(locationRunB)
				}, 300)
				setTimeout(() => {
					this.conbuffer(locationRunC)
				}, 900)
			},
			// 初始蓝牙
			initialMotor() {
				// 保持屏幕常亮
				uni.setKeepScreenOn({
					keepScreenOn: true
				});
				uni.showLoading({
					mask: true,
					title: '连接设备中...'
				});
				this.lanname = this.vuex_devicename
				this.deviceId = this.vuex_deviceId
				setTimeout(() => {
					uni.hideLoading()
				}, 3000)
				// 蓝牙服务
				this.getBLEDeviceServices()
				// 断开设备
				uni.onBLEConnectionStateChange((res) => {
					// 该方法回调中可以用于处理连接意外断开等异常情况
					if (res.connected !== true) {
						console.log('意外断开');
						this.lanname = ''
						uni.$u.vuex('vuex_devicename', '')
						uni.$u.vuex('vuex_deviceId', '')
					}
				})
			},
			// 初始化
			iniIFFn() {
				this.infIF = true
			},
			// 初始化电机确定
			cinfconfirmIF() {
				clearInterval(this.timerTmei)
				this.iniFn()
				this.infIF = false
			},
			// 初始化电机取消
			infcancelIF() {
				this.infIF = false
			},
			// 脉冲清零归零模式
			iniFn() {
				uni.showToast({
					title: '正在初始化...',
					icon: 'loading',
					mask: true,
					duration: 4000
				});
				// 驱动器上电初始化
				let iniA = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x01', '0x57', '0xDE']
				// 驱动器正常运行，但电机未使能，松开刹车
				let iniB = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x03', '0xD6', '0x1F']
				// 电机给电，处于可运行状态
				let iniC = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x0F', '0xD6', '0x1A']
				// 设置回零模式 01 06 60 60 00 06 17 D6
				let iniD = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x06', '0x17', '0xD6']
				// 设定回零方式 01 10 60 7C 00 08 10 00 00 03 E8 00 01 00 00 00 64 03 E8 00 00 00 64
				let iniE = ['0x01', '0x10', '0x60', '0x7C', '0x00', '0x08', '0x10', '0x00', '0x00', '0x03', '0xE8',
					'0x00', '0x01', '0x00', '0x00', '0x00', '0x64', '0x03', '0xE8', '0x00', '0x00', '0x00', '0x64',
					'0x09', '0x42'
				]
				// 开始归零
				let iniF = ['0x01', '0x06', '0x60', '0x40', '0x00', '0x5F', '0xD6', '0x26']
				this.conbuffer(iniA)
				setTimeout(() => {
					this.conbuffer(iniB)
				}, 300)
				setTimeout(() => {
					this.conbuffer(iniC)
				}, 600)
				setTimeout(() => {
					this.conbuffer(iniD)
				}, 900)
				setTimeout(() => {
					this.conbuffer(iniE)
				}, 1200)
				setTimeout(() => {
					this.conbuffer(iniF)
					setTimeout(() => {
						this.verticalZeroingYY()
					}, 300)
				}, 1500)
			},
			// 横向初始化
			verticalZeroingYY() {
				// 暂停电机运行
				let inia = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x0F', '0xD7', '0x8A']
				// 设置位置模式
				let inib = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x01', '0x56', '0x14']
				// 设置点位参数 1200转速
				// let inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x00',
				// 	'0xC8', '0x00', '0x64', '0x00', '0x64', '0x69', '0x83'
				// ]
				let inic = []
				if (this.rotatvalue == '1200') {
					// 设置点位参数 1200转速
					inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x00',
						'0xC8', '0x00', '0x64', '0x00', '0x64', '0x69', '0x83'
					]
				}
				this.conbuffer(inia)
				setTimeout(() => {
					this.conbuffer(inib)
				}, 300)
				setTimeout(() => {
					this.conbuffer(inic)
				}, 600)
				setTimeout(() => {
					this.aLLBrakeFnxx()
				}, 900)
			},
			// 切换模式
			switchMode() {
				if (!this.modeSwitching) {
					uni.showToast({
						title: '设备状态错误',
						icon: "error",
						mask: true,
						duration: 1500
					});
					return
				}
				uni.showToast({
					title: '切换模式中...',
					icon: 'loading',
					mask: true,
					duration: 2000
				});
				console.log('切换模式', this.rotatvalue);
				// 暂停电机运行
				let inia = ['0x01', '0x06', '0x60', '0x40', '0x01', '0x0F', '0xD7', '0x8A']
				// 设置位置模式
				let inib = ['0x01', '0x06', '0x60', '0x60', '0x00', '0x01', '0x56', '0x14']
				let inic = []
				if (this.rotatvalue == 600) {
					// 设置点位参数 600转速
					inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x00',
						'0x64', '0x00', '0x64', '0x00', '0x64', '0xF9', '0x9B'
					]
				}
				if (this.rotatvalue == 1200) {
					// 设置点位参数 1200转速
					inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x00',
						'0xC8', '0x00', '0x64', '0x00', '0x64', '0x69', '0x83'
					]
				}
				if (this.rotatvalue == 1800) {
					// 设置点位参数 1200转速
					inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x01',
						'0x2C', '0x00', '0x64', '0x00', '0x64', '0x18', '0x44'
					]
				}
				if (this.rotatvalue == 2400) {
					// 设置点位参数 1200转速
					inic = ['0x01', '0x10', '0x60', '0x81', '0x00', '0x04', '0x08', '0x00', '0x00', '0x01',
						'0x90', '0x00', '0x64', '0x00', '0x64', '0x49', '0x9F'
					]
				}
				this.conbuffer(inia)
				setTimeout(() => {
					this.conbuffer(inib)
				}, 300)
				setTimeout(() => {
					this.conbuffer(inic)
				}, 600)
			},
			// 输入蓝牙数据
			conbuffer(data) {
				let msg = data
				// console.log('发送数据格式蓝牙', data);
				// 向蓝牙设备发送一个0x00的16进制数据
				const buffer = new ArrayBuffer(msg.length)
				const dataView = new DataView(buffer)
				// dataView.setUint8(0, 0)
				for (var i = 0; i < msg.length; i++) {
					// dataView.setUint8(i, msg.charAt(i).charCodeAt())
					dataView.setUint8(i, msg[i]);
				}
				this.sendMsgToKey(buffer)
			},
			//监听消息变化++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			listenValueChange(data) {
				setTimeout(() => {
					uni.onBLECharacteristicValueChange(res => {
						if (this.lanname != '') {
							let resHex = this.ab2hex(res.value)
							this.monitoringInformationProcessing(resHex)
						} else {
							this.monitoringInformationProcessing(res)
						}
					})
				}, 300)
			},
			monitoringInformationProcessing(res) {
				let resHex = res
				console.log('监听数据', resHex, resHex.length, resHex.substr(6, 4));
				//电机状态
				if (resHex.length == 34) {
					// 电机初始化状态
					if (resHex.substr(6, 4) == '1037') {
						// 初始化
						this.lightsOn = true
						// 切换模式
						this.modeSwitching = true
						console.log('电机初始化状态');
					}
					// 电机运行状态
					if (resHex.substr(6, 4) == '1237') {
						// 切换模式判断
						this.modeSwitching = false
						console.log('电机运行状态');
					}
					// 电机暂停状态
					if (resHex.substr(6, 4) == '1437') {
						// 切换模式判断
						this.modeSwitching = true
						console.log('电机暂停状态');
						setTimeout(() => {
							clearInterval(this.timerTmei)
						}, 100)
					}
					// 获取脉冲
					let str = resHex.substr(14, 8)
					// 脉冲圈数
					this.numberOfCircles = (this.hexToDecimal(str) / 1000 / this.reductionRatio).toFixed(1)
					console.log('脉冲', this.numberOfCircles);

				}
			},
			//获取蓝牙的所有服务
			getBLEDeviceServices() {
				setTimeout(() => {
					uni.getBLEDeviceServices({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.vuex_deviceId,
						success: (res) => {
							console.log('获取vuex_deviceId', this.vuex_deviceId);
							console.log('获取蓝牙所有服务', res);
							//E95D93AF-251D-470A-A062-FA1922DFA9A8
							//6E400001-B5A3-F393-E0A9-E50E24DCCA9E
							res.services.forEach((item) => {

								if (item.uuid.indexOf("0000FFF0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("0000FFE0") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
								if (item.uuid.indexOf("00001000") != -1) {
									this.serviceId = item.uuid;
									//获取特征
									this.getBLEDeviceCharacteristics()
								}
							})
						}
					})
				}, 1000)
			},
			//获取蓝牙特征
			getBLEDeviceCharacteristics() {
				console.log('获取蓝牙特征值', this.deviceId, this.serviceId, );
				setTimeout(() => {
					uni.getBLEDeviceCharacteristics({
						// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
						deviceId: this.deviceId,
						// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
						serviceId: this.serviceId,
						success: (res) => {

							this.characteristics = res.characteristics
							res.characteristics.forEach((item) => {

								if (item.uuid.indexOf("FFF2") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("FFE1") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("0000FFE1") != -1) {
									this.characteristicId = item.uuid
									//利用传参的形势传给下面的notify，这里的uuid如果都需要用到，就不用做判断了，建议使用setTimeout进行间隔性的调用此方法
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								if (item.uuid.indexOf("0000FFF1") != -1) {
									this.characteristicId = item.uuid
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
								// EW-DTU02
								if (item.uuid.indexOf("00001001") != -1) {
									this.fff = item.uuid
								}
								if (item.uuid.indexOf("00001002") != -1) {
									this.characteristicId = item.uuid
									this.notifyBLECharacteristicValueChange(item.uuid)
								}
							})
						},
						fail: (res) => {
							console.log(res)
						}
					})
				}, 1000)
			},
			// 修改数组里面指定对象
			updateItemById(array, id, newData) {
				return array.map(item => {
					if (item.id === id) {
						return {
							...item,
							...newData
						};
					}
					return item;
				});
			},
			// 删除指定字符串最后面
			removeTrailingSubstring(str, suffix) {
				if (!str || !suffix) return str;

				const strLength = str.length;
				const suffixLength = suffix.length;

				// 检查字符串是否以指定的子串结尾
				if (strLength >= suffixLength &&
					str.substring(strLength - suffixLength) === suffix) {
					return str.substring(0, strLength - suffixLength);
				}

				return str;
			},
			roundAndTrim(num) {
				// 四舍五入到6位小数
				const rounded = num.toFixed(5);
				// 去除末尾的零和小数点（如果后面全是零）
				return rounded.replace(/(\.\d*?[1-9])0+$|\.0+$/, '$1');
			},
			// 16进制转2进制
			hexToBinaryW(hexString) {
				if (!/^[0-9A-Fa-f]+$/.test(hexString)) {
					throw new Error("Invalid hexadecimal string");
				}
				const decimal = parseInt(hexString, 16);
				return decimal.toString(2);
			},
			// 10进制转32位二进制补码
			NumberOf1(num) {
				// 获取负数的绝对值
				const absoluteValue = Math.abs(num);

				// 将绝对值转换为32位二进制字符串
				let binaryString = absoluteValue.toString(2);

				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				// 对二进制字符串取反
				const invertedBinaryString = binaryString.split('').map(bit => bit === '0' ? '1' : '0').join('');

				// 将取反后的二进制字符串转换为数字并加1
				const twosComplement = parseInt(invertedBinaryString, 2) + 1;

				// 再次将补码转换为32位二进制字符串
				binaryString = twosComplement.toString(2);
				// 确保二进制字符串长度为32位
				while (binaryString.length < 32) {
					binaryString = '0' + binaryString;
				}

				return binaryString;
			},
			// 二进制补码转16进制
			binaryToHex(binaryStr) {
				// 确保二进制字符串是32位
				if (binaryStr.length !== 32) {
					throw new Error('Binary string must be 32 bits long');
				}

				// 将二进制字符串转换为数字
				var number = parseInt(binaryStr, 2);

				// 转换为16进制并返回结果
				return number.toString(16);
				// 示例使用
				// var binaryStr = '010101010101010101010101010101010'; // 32位二进制补码
				// var hexStr = binaryToHex(binaryStr);
			},
			//数组求平均
			averageSum(arr) {
				if (arr.length === 0) {
					return 0; // 当数组为空时，平均值为0
				}

				let sum = 0;
				for (let i = 0; i < arr.length; i++) {
					sum += arr[i];
				}

				return sum / arr.length;
			},
			// 长度不够补0
			strRepair(str, nub) {
				let nubm = nub * 1
				let strif = str + ''
				if (strif.length < nubm) {
					for (let i = 0; i < nubm - str.length; i++) {
						strif = '0' + strif
					}
				}
				return strif
			},
			//给每个数组添加0x
			ocstr(data) {
				let arr = []
				for (let i = 0; i < data.length; i++) {
					data[i] = '0x' + data[i]
				}
				return data
			},
			// 每2个字符串为一个元素数组
			chunkStringByTwo(str) {
				const result = [];
				for (let i = 0; i < str.length; i += 2) {
					result.push(str.slice(i, i + 2));
				}
				return result;
			},
			// 处理ASCLL 30 -00
			ascllFn(data) {
				let str = data + ''
				let arr = this.chunkStringByTwo(str)

				for (let i = 0; i < arr.length; i++) {
					if (arr[i] == '00') {
						arr[i] = '30'
					}
				}
				let arrnew = arr

				let strnre = ''
				for (let i = 0; i < arrnew.length; i++) {
					strnre += arrnew[i]
				}
				return strnre
			},
			// CRC16校验
			crc16(dataHexString) {
				const dataBytes = [];
				for (let i = 0; i < dataHexString.length; i += 2) {
					dataBytes.push(parseInt(dataHexString.substr(i, 2), 16));
				}

				let crc = 0xFFFF;
				const polynomial = 0xA001;

				for (const byte of dataBytes) {
					crc ^= byte;
					for (let i = 0; i < 8; i++) {
						if (crc & 0x0001) {
							crc = ((crc >> 1) ^ polynomial) & 0xFFFF;
						} else {
							crc >>= 1;
						}
					}
				}
				let crcstr = crc.toString(16).toUpperCase();
				if (crcstr.length % 2 == 0) {
					let result = crcstr.match(/.{1,2}/g)
					return result;
				} else {
					let str = '0' + crcstr
					let result = str.match(/.{1,2}/g)
					return result;
				}
			},
			// 16进制转10进制
			hexToDecimal(hex) {
				return parseInt(hex, 16);
			},
			// 10进制转16进制
			decimalToHex(data) {
				let decimal = data * 1
				let hex = decimal.toString(16).toUpperCase();
				3
				if (hex.length % 2 !== 0) {
					return '0' + hex
				} else {
					return hex
				}
				// return decimal.toString(16).toUpperCase();
			},
			// 16进制转字符串 ASCII码
			hexToString(hex) {
				let str = '';
				for (let i = 0; i < hex.length; i += 2) {
					let charCode = parseInt(hex.substr(i, 2), 16);
					str += String.fromCharCode(charCode);
				}
				return str;
			},

			//字符串转16进制
			stringToHex(data) {
				let str = data + ''
				return str.split('').map(function(char) {
					return char.charCodeAt(0).toString(16).padStart(2, '0');
				}).join('');
			},
			// 16进制转汉字
			hexToChinese(hex) {
				var str = '';
				for (var i = 0; i < hex.length / 4; i++) {
					var codePoint = parseInt(hex.substr(i * 4, 4), 16); // 获取每四位的十六进制值并转换成十进制
					str += String.fromCharCode(codePoint); // 根据Unicode编码生成对应的字符
				}
				return str;
			},
			// 汉字转16进制
			convertToHex(str) {
				let result = '';
				for (let i = 0; i < str.length; i++) {
					result += str.charCodeAt(i).toString(16);
				}
				return result;
			},
			// 随机数
			getRandomNumber(min, max) {
				return Math.floor(Math.random() * (max - min + 1)) + min;
			},
			// 删除最小的前面几个数字
			removeSmallestN(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最前面的n个数字
				sorted.splice(0, n);
				return sorted;
			},
			// 删除最大的后面几个数字
			removeMax(arr, n) {
				// 对数组进行升序排序
				const sorted = arr.sort((a, b) => a - b);
				// 删除最后面的n个数字
				sorted.splice(-n);
				return sorted;
			},
			// ArrayBuffer转16进度字符串示例
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			/* 向设备发送消息(分包发送，单包20字节，递归发送)
			 */
			sendMsgToKey(buffer) {
				var that = this //vue中的this
				const packageSize = 20 //分包大小
				if (buffer.byteLength <= 20) { //如果小于20直接发送，不再继续调用
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						// characteristicId: that.fff, //第二步写入的特征值
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: buffer,
						writeType: 'write',
						success: (res) => {
							//此时设备已接收到你写入的数据
							// console.log('写入11111');

						},
						fail: (err) => {
							console.log('传输失败', err)
							this.lanname = this.vuex_devicename
						},
						complete: function() {}
					})
				} else { //如果大于20发送完成后继续递归调用
					var newData = buffer.slice(20)
					var writeBuffer = buffer.slice(0, 20)
					uni.writeBLECharacteristicValue({
						// 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
						deviceId: that.deviceId,
						// 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
						serviceId: that.serviceId,
						// 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
						characteristicId: that.fff, //第二步写入的特征值
						// 这里的value是ArrayBuffer类型
						value: writeBuffer,
						writeType: 'write',
						success: function(res) {
							// console.log('写入22222');
							//写入后继续递归调用发送剩下的数据
							setTimeout(() => {
								that.sendMsgToKey(newData)
							}, 100)
						},
						fail: (err) => {
							this.lanname = this.vuex_devicename
							console.log('传输失败', err)
						},
						complete: function() {}
					})
				}
			},
			// 启用 notify 功能
			notifyBLECharacteristicValueChange(characteristicId) {
				console.log('启用 notify 功能');
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,

					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: this.serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: this.characteristicId,
					success: (res) => {
						console.log('蓝牙名字', res);
						// vuex
						// uni.$u.vuex('vuex_devicename', this.vuexlist.name)
						uni.hideLoading()
						this.listenValueChange()
						uni.showToast({
							title: '设备已连接',
							mask: true,
							duration: 1000
						});
						this.iniFn()
						console.log('蓝牙服务已开启');
					},
					fail: (res) => {
						uni.hideLoading()
						uni.showToast({
							title: '连接设备失败',
							icon: 'fail',
							mask: true,
							duration: 1000
						});

					}
				})
			},
			// 删除数组
			removeById(arr, id) {
				for (let i = 0; i < arr.length; i++) {
					if (arr[i].id === id) {
						arr.splice(i, 1);
						break;
					}
				}
				return arr;
			},
			// 生Id
			nanoid(size = 21) {
				let id = ''
				let i = size
				while (i--) {
					id += this.urlAlphabet[(Math.random() * 64) | 0]
				}
				return id
			},
			// 蓝牙
			tobelFn() {
				clearInterval(this.timerTmei)
				//在起始页面跳转到test.vue页面并传递参数
				uni.navigateTo({
					url: '/pages/index/devBEL'
				});

			},
			//断开连接
			lampRFn() {
				clearInterval(this.timerTmei)
				uni.closeBLEConnection({
					deviceId: this.vuex_deviceId,
					success: (res) => {
						uni.showToast({
							title: '设备已断开',
							icon: 'success',
							mask: true,
							duration: 1000
						});
						this.lanname = ''
						uni.$u.vuex('vuex_devicename', '')
					}
				})
			},
		}
	}
</script>
<style scoped lang="scss">
	// 内容
	.concent_box {
		padding: 30rpx;

		// 连接设备
		.inibox {
			margin: 20rpx 0;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.lights-box {
				width: 300rpx;
				text-align: center;
				font-size: 30rpx;
				padding: 20rpx 0;
				border-radius: 200rpx;
			}

			.lights-off {
				color: #7b7d78;
				background-color: #e3e5db;
			}

			.lights-on {
				color: #ffffff;
				background-color: #766793;
			}

			// 初始化
			.inibox_in {
				width: 300rpx;

				.inibox_tt_a {
					text-align: center;
					color: #bd241a;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #eee4e2;
				}

				.inibox_tt_b {
					text-align: center;
					color: #ffffff;
					font-size: 30rpx;
					padding: 20rpx 0;
					border-radius: 200rpx;
					background-color: #00b457;
				}

				.inibox_ttacv {
					color: #ffffff;
					background-color: #d0d4d4;
				}
			}

			.inibox_acv {
				color: #ffffff;
				background-color: #d0d4d4;
			}
		}


		.lamp_a {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0 30rpx;

			.lamp_l_a {
				width: 50rpx;
				height: 50rpx;
				border-radius: 100rpx;
				background-color: #c2e2cc;
				box-shadow: inset 0 0 20rpx rgba(0, 0, 0, 0.3);
			}

			.lamp_r_a {
				width: 50rpx;
				height: 50rpx;
				border-radius: 100rpx;
				background-color: #ff0000;
				box-shadow: inset 0 0 20rpx rgba(0, 0, 0, 0.3);
			}
		}
	}

	// 转速
	.rotatzhuns {
		padding: 10rpx;
		margin: 20rpx 0;
		border-radius: 10rpx;
		background-color: rgba(#9accb9, 0.1);
		border: rgba(#9accb9, 0.2) solid 1rpx;

		.rotatzhflax {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.zhunsbtn {
			width: 100%;
			font-size: 40rpx;
			background: rgba(#9accb9, 0.5);
			border: 1rpx solid rgba(#9accb9, 0.3);
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: all 0.2s;
			cursor: pointer;
			font-weight: 500;
			color: rgba(#383d41, 0.8);

			&:active {
				background-color: #9accb9;
				opacity: 0.6;
				transform: scale(0.8);
			}
		}
	}

	// 圈数
	.rotatquans {
		padding: 10rpx;
		margin: 20rpx 0;
		border-radius: 10rpx;
		background-color: rgba(#aaaaff, 0.1);
		border: rgba(#aaaaff, 0.2) solid 1rpx;

		.rotatzhflax {
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.zhunsbtn {
			width: 100%;
			font-size: 40rpx;
			border-radius: 8rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: all 0.2s;
			cursor: pointer;
			font-weight: 500;
			color: rgba(#51517a, 0.8);
		}
	}

	// 运行距离
	.card-modu_bnox {
		border-radius: 16rpx;
		// padding-left: 20rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		// background-color: rgba(#bcddea, 0.1);
		// border: rgba(#bcddea, 1) solid 1rpx;

		// 输入框
		.indats {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: space-between;
			background-color: rgba(#c3e6cb, 0.5);
			border: rgba(#c3e6cb, 0.2) solid 1rpx;
			font-size: 45rpx;
			border-radius: 10rpx;


			.card-box {
				width: 360rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-radius: 10rpx;
				padding: 20rpx;

				/* 输入框 */
				.card-input {
					flex: 1;
					width: 260rpx;
					margin: 5rpx;
					font-size: 50rpx;
					color: #d9ffe2;
					text-align: center;
					border: 1rpx solid #c3e6cb;
					background-color: #155724;
					border-radius: 8rpx;
					margin-right: 16rpx;

				}

				/* 单位 */
				.unit {
					width: 60rpx;
					color: #155724;
					text-align: center;
					margin-right: 25rpx;
				}
			}


			/* 运行按钮（绿色） */
			.run-btt {
				width: 400rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background-color: rgba(#c3e6cb, 1);
				color: #155724;
			}

			/* 占位符样式 */
			.placeholder-style {
				color: #999;
				font-size: 40rpx;
			}
		}

		.card-module {
			font-size: 35rpx;

			// 上升
			.card-container_up {
				display: flex;
				align-items: center;
				padding: 20rpx;

				/* 上升按钮（绿色） */
				.rise-btn {
					width: 200rpx;
					font-size: 55rpx;
					background: rgba(#2ecc71, 0.1);
					border: 1rpx solid rgba(#2ecc71, 0.3);
					border-radius: 8rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					transition: all 0.2s;
					cursor: pointer;

					.btn-text {
						font-weight: 500;
						color: #2ecc71;
					}

					&:active {
						background-color: #00c35e;
						opacity: 0.6;
						transform: scale(0.8);
					}
				}
			}

			// 下降
			.card-container_dn {
				display: flex;
				align-items: center;
				padding: 20rpx;

				/* 下降按钮（黄色） */
				.rise-pd {
					width: 200rpx;
					font-size: 55rpx;
					background: rgba(#ffaa00, 0.1);
					border: 1rpx solid rgba(#ffaa00, 0.3);
					border-radius: 8rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					transition: all 0.2s;
					cursor: pointer;

					.btn-text {
						font-weight: 500;
						color: #ffaa00;
					}

					&:active {
						background-color: #ffd145;
						opacity: 0.6;
						transform: scale(0.8);
					}
				}
			}

			// 运行
			.card-container_Run {
				display: flex;
				align-items: center;
				justify-content: center;

				.clean-game-btn {
					width: 180rpx;
					padding: 30rpx 10rpx;
					font-size: 50rpx;
					line-height: 180rpx;
					font-weight: bold;
					text-align: center;
					border-radius: 20rpx;
					box-shadow:
						0 4rpx 12rpx rgba(0, 0, 0, 0.08),
						inset 0 1rpx 2rpx rgba(255, 255, 255, 0.8);
					transition: all 0.2s ease;
				}

				.clean-game-btn.success {
					color: #155724;
					background-color: rgba(#c3e6cb, 0.3);
					border: 1rpx solid rgba(#c3e6cb, 1);
				}

				/* 点击效果 */
				.clean-game-btn:active {
					transform: translateY(5rpx);
					transform: scale(0.9);
					background: #76b091;
					box-shadow:
						0 2rpx 8rpx rgba(0, 0, 0, 0.08),
						inset 0 1rpx 2rpx rgba(255, 255, 255, 0.8);

				}
			}
		}

		.indah {
			height: 100rpx;
		}
	}

	// 控制暂停按钮
	.control-btn {
		font-size: 45rpx;
		padding: 15rpx 30rpx;
		border-radius: 30rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		transition: all 0.2s ease;
		color: #ffffff;
		background: #be112b;

		/* 按压效果 */
		&:active {
			background: rgba(#a60e27, 1);
			transform: scale(0.9);
		}
	}

	// 初始位置
	.initial_position {
		padding: 10rpx;
		margin: 20rpx 0;
		font-size: 40rpx;
		border-radius: 20rpx;
		color: #0b555f;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: rgba(#c3e2eb, 0.1);
		border: 1rpx solid rgba(#bee5eb, 1);

		.real_r_a {
			width: 210rpx;
			padding: 10rpx;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: rgba(#bee5eb, 0.2);

			.real_rin {
				width: 150rpx;
				padding: 10rpx;
				border: 1rpx solid rgba(#bee5eb, 1);
				border-radius: 10rpx;
				background-color: rgba(#bee5eb, 0.1);
			}

			.real_rtt {
				width: 110rpx;
				text-align: center;
				color: rgba(#062c33, 0.5);
				font-size: 40rpx;
			}
		}
	}


	// 初始位置
	.chuistonflzx {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.chuistsp {
			width: 350rpx;
			padding: 10rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}



	// 行走圈数

	.real_simu_a {
		padding: 10rpx;
		margin: 20rpx 0;
		font-size: 40rpx;
		border-radius: 20rpx;
		color: #004085;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: rgba(#b8daff, 0.1);
		border: 1rpx solid rgba(#b8daff, 1);

		.real_r_a {
			width: 340rpx;
			padding: 0 20rpx;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: rgba(#b8daff, 0.2);

			:nth-child(1) {
				font-size: 80rpx;
				margin-right: 10rpx;
			}

			:nth-child(2) {
				color: rgba(#004085, 0.5);
				font-size: 40rpx;
				padding-top: 25rpx;
			}
		}
	}

	.real_simu_b {
		padding: 10rpx;
		margin: 20rpx 0;
		font-size: 40rpx;
		border-radius: 20rpx;
		color: #155724;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: rgba(#c3e6cb, 0.1);
		border: 1rpx solid rgba(#c3e6cb, 1);

		.real_r_a {
			width: 280rpx;
			padding: 0 50rpx;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: rgba(#c3e6cb, 0.2);

			:nth-child(1) {
				font-size: 80rpx;
				margin-right: 10rpx;
			}

			:nth-child(2) {
				color: rgba(#155724, 0.5);
				font-size: 40rpx;
				padding-top: 25rpx;
			}
		}
	}

	.real_simu_c {
		padding: 10rpx;
		margin: 20rpx 0;
		font-size: 40rpx;
		border-radius: 20rpx;
		color: #856404;
		display: flex;
		align-items: center;
		justify-content: space-between;
		background-color: rgba(#ffeeba, 0.1);
		border: 1rpx solid rgba(#ffeeba, 1);

		.real_r_a {
			width: 300rpx;
			padding: 0 40rpx;
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: rgba(#ffeeba, 0.2);

			:nth-child(1) {
				font-size: 80rpx;
				margin-right: 10rpx;
			}

			:nth-child(2) {
				color: rgba(#856404, 0.5);
				font-size: 40rpx;
				padding-top: 25rpx;
			}
		}
	}
</style>
<style>
	@font-face {
		font-family: 'MyFont';
		src: url('@/static/fonts/LED.otf');
	}

	page {
		background-color: #ffffff;
	}
</style>